package com.study.webapp.jdk8;


import java.util.concurrent.locks.LockSupport;

/**
 * 第一个线程是从1-26，第二个线程是从A到Z,然后要求这两个线程同时运行，交替输出，顺序打印。
 */
public class TestQuestion {
    /**
     * 方法一，使用LockSupport
     */
    static class method1 {
        static Thread t1 = null;
        static Thread t2 = null;
        public static void main(String[] args) {
            char[] a1 = "123456".toCharArray();
            char[] a2 = "abcdef".toCharArray();
            t1  = new Thread(new Runnable() {
                @Override
                public void run() {
                    for (char c : a1) {
                        System.out.print(c);
                        LockSupport.unpark(t2);
                        LockSupport.park();
                    }
                }
            },"t1");

            t2 = new Thread(new Runnable() {
                @Override
                public void run() {
                    for(char c :a2) {
                        LockSupport.park();
                        System.out.print(c);
                        LockSupport.unpark(t1);
                    }
                }
            },"t2");
            t1.start();
            t2.start();
        }
    }

    /**
     * 使用synchronized,notify
     */
    static class method2 {
        public static void main(String[] args) {
            final Object o = new Object();
            char[] a1 = "123456".toCharArray();
            char[] a2 = "abcdef".toCharArray();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    synchronized(o) {
                        for (char c :a1) {
                            System.out.print(c);
                            try {
                                o.notify();
                                o.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        o.notify();
                    }
                }
            },"t1").start();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    synchronized(o) {
                        for (char c :a2) {
                            System.out.println(c);
                            try {
                                o.notify();
                                o.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        o.notify();
                    }
                }
            },"t2").start();
        }
    }
}
